package com.huayi.website.controller.manage;

import com.alibaba.fastjson.JSONObject;


import com.huayi.website.utils.RandomUtils;
import com.huayi.website.utils.ResultVo;
import com.huayi.website.utils.UploadImageResult;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：
 * 上传文件AJAX
 *
 * @author qlp
 * @date 2018-12-20 5:31 PM
 */
@RestController
public class UploadAjaxController {


    /**
     * 上传图片
     *
     * @return
     */
    @RequestMapping(value = "/upload_image", method = RequestMethod.POST)
    public ResultVo<UploadImageResult> uploadImage(MultipartFile file) throws IOException {

        if (file.isEmpty()) return new ResultVo<>(400, "请选择图片");

//        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
//        String fileName = file.getOriginalFilename();
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        ArrayList<String> a = new ArrayList<>();
        a.add("gif");
        a.add("jpg");
        a.add("jpeg");
        a.add("png");
        if (a.contains(fileSuffix) == false) return new ResultVo<>(400, "不支持的格式");

        //appid配置
        Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
        String qiniu_img_domain = properties.getProperty("qiniu_img_domain");
        String qiniu_access_key = properties.getProperty("qiniu_access_key");
        String qiniu_secret_key = properties.getProperty("qiniu_secret_key");
        String qiniu_bucket = properties.getProperty("qiniu_bucket");


        //...生成上传凭证，然后准备上传
//        String accessKey = "MklTiy5YNow7dVZHYrJTm6WLN89S3yzhehRPfJtW";
//        String secretKey = "eLMI-BShHg2z0EGwJ9hd3ZWyf0HZDzfyXNaLuxrF";
//        String bucket = "huayikeji-file";
        Auth auth = Auth.create(qiniu_access_key, qiniu_secret_key);

        String upToken = auth.uploadToken(qiniu_bucket);//上传的凭据

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());

        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;


//        Response response = uploadManager.put(file, key, upToken);

        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            //解析上传成功的结果
           //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);// null;
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            ResultVo<UploadImageResult> result = new ResultVo<>();
            result.setCode(0);
            UploadImageResult uploadImageResult = new UploadImageResult();
            uploadImageResult.setSrc(qiniu_img_domain + putRet.key);
            result.setData(uploadImageResult);
            return result;

        } catch (QiniuException ex) {
            Response r = ex.response;

            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
                return new ResultVo<>(500, r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                return new ResultVo<>(500, "图片上传错误");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVo<>(400, "图片格式错误");
        }


    }

    /**
     * 上传base64图片
     * 上传到七牛云
     *
     * @param image
     * @return
     * @throws IOException
     */
    //    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/upload_image_base64", method = RequestMethod.POST)
    public ResultVo<UploadImageResult> uploadImage2(@RequestParam String image) throws IOException {
        if (StringUtils.isEmpty(image)) return new ResultVo<>(400, "请选择图片");


        String pattern = "data:image/(.*);base64,";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(image);
        String suffix = "";
        while (matcher.find()) {
            suffix = matcher.group(1);
        }
        if (StringUtils.isEmpty(suffix)) return new ResultVo<>(400, "请选择图片文件");

        //七牛上传参数
        String qiniu_img_domain = "";
        String qiniu_access_key = "";
        String qiniu_secret_key = "";
        String qiniu_bucket = "";
        try {
            //appid配置
            Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
            if(properties.isEmpty())
                return new ResultVo<>(400, "缺少七牛云配置");
             qiniu_img_domain = properties.getProperty("qiniu_img_domain");
             qiniu_access_key = properties.getProperty("qiniu_access_key");
             qiniu_secret_key = properties.getProperty("qiniu_secret_key");
             qiniu_bucket = properties.getProperty("qiniu_bucket");
        }catch (Exception e){
            return new ResultVo<>(400, "缺少七牛云配置");
        }



        String key = RandomUtils.randomString(32);
        image = image.replace("data:image/" + suffix + ";base64,", "");


        //...生成上传凭证，然后准备上传
//        String accessKey = "MklTiy5YNow7dVZHYrJTm6WLN89S3yzhehRPfJtW";
//        String secretKey = "eLMI-BShHg2z0EGwJ9hd3ZWyf0HZDzfyXNaLuxrF";
//        String bucket = "huayikeji-file";
        Auth auth = Auth.create(qiniu_access_key, qiniu_secret_key);

        String upToken = auth.uploadToken(qiniu_bucket);//上传的凭据

        /**上传到七牛云**/
        String url = "https://up-z2.qiniup.com/putb64/-1/key/" + UrlSafeBase64.encodeToString(key);
        okhttp3.RequestBody rb = okhttp3.RequestBody.create(null, image);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + upToken)
                .post(rb).build();
//        System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);

        ResultVo<UploadImageResult> result = new ResultVo<>();
        result.setCode(0);
        UploadImageResult uploadImageResult = new UploadImageResult();
        uploadImageResult.setSrc(qiniu_img_domain + key);
        result.setData(uploadImageResult);

        return result;

    }

    @RequestMapping(value = "/upload_video_base64", method = RequestMethod.POST)
    public ResultVo<UploadImageResult> uploadVideo(MultipartFile file) throws IOException {
        if (file.isEmpty()) return new ResultVo<>(400, "请选择mp4视频文件");

        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (fileSuffix.equalsIgnoreCase("MP4") == false) return new ResultVo<>(400, "只支持mp4视频文件上传");

        //appid配置
        Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
        String qiniu_img_domain = properties.getProperty("qiniu_img_domain");
        String qiniu_access_key = properties.getProperty("qiniu_access_key");
        String qiniu_secret_key = properties.getProperty("qiniu_secret_key");
        String qiniu_bucket = properties.getProperty("qiniu_bucket");

        //...生成上传凭证，然后准备上传
        Auth auth = Auth.create(qiniu_access_key, qiniu_secret_key);

        String upToken = auth.uploadToken(qiniu_bucket);//上传的凭据

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());

        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;


//        Response response = uploadManager.put(file, key, upToken);

        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            //解析上传成功的结果
            //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            DefaultPutRet putRet = null;
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            ResultVo<UploadImageResult> result = new ResultVo<>();
            result.setCode(0);
            UploadImageResult uploadImageResult = new UploadImageResult();
            uploadImageResult.setSrc(qiniu_img_domain + putRet.key);
            result.setData(uploadImageResult);
            return result;

        } catch (QiniuException ex) {
            Response r = ex.response;

            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
                return new ResultVo<>(500, r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                return new ResultVo<>(500, "视频上传错误");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVo<>(400, "视频格式错误");
        }

    }

//    @RequestMapping(value = "/upload_qiniu_token", method = RequestMethod.POST)
//    public ApiResult<String> uploadAuth() {
//        String accessKey = "MklTiy5YNow7dVZHYrJTm6WLN89S3yzhehRPfJtW";
//        String secretKey = "eLMI-BShHg2z0EGwJ9hd3ZWyf0HZDzfyXNaLuxrF";
//        String bucket = "huayikeji-file";
//        Auth auth = Auth.create(accessKey, secretKey);
//
//        String upToken = auth.uploadToken(bucket);//上传的凭据
//
//        return new ApiResult<>(0, "", upToken);
//    }


}
